// 改文件用于创建Vuex中最为核心的store
import axios from "axios"
import { nanoid } from "nanoid"
import Vue from "vue"
// 引入Vuex
import Vuex from "vuex"
// 使用Vuex插件
Vue.use(Vuex)
// 准备actions==>用于响应组件中的动作

//求和功能相关配置
const countOptions = {
    namespaced: true,
    state: {
        sum: 0,
        name: "SONG",
        age: 18,
    },
    getters: {
        bigSum(state) {
            return state.sum*10
        }
    },
    actions: {
        plus(context, value) {
            context.commit("PLUS", value)
        },
        reduce(context, value) {
            context.commit("REDUCE", value)
            context.dispatch("demo1", value)
        },
        plusOdd(context, value) {
            if (context.state.sum % 2) {
                context.commit("PLUS", value)
            }
        },
        plusWait(context, value) {
            setTimeout(() => {
                context.commit("PLUS", value)
            }, 2000)
        },
        demo1(context, value) {
            console.log("demo1", context)
        }
    },
    mutations: {
        PLUS(state, value) {
            state.sum += value
        },
        REDUCE(state, value) {
            state.sum -= value
        },
    },
}
// 热源管理相关配置
const personOptions = {
    namespaced: true,
    state: {
        personList: [
            {
                id: "001",
                name: "宋"
            }
        ]
    },
    getters: {
        firstPersonName(state) {
            return state.personList[0].name
        }
    },
    actions: {
        addPersonLiu(context, value) {
            if (value.name.indexOf("刘") === 0) {
                context.commit("ADD_PERSON", value)
            }else{
                alert("添加的人必须姓刘")
            }
        },
        addPersonServer(context){
            axios.get("https://api.uixsj.cn/hitokoto/get?type=social")
            .then(res=>{
                context.commit("ADD_PERSON",{id:nanoid(),name:res.data})
            })
        }
    },
    mutations: {
        ADD_PERSON(state, value) {
            state.personList.unshift(value)
        }
    },
}


// 创建store
export default new Vuex.Store({
    modules: {
        countAbout: countOptions,
        personAbout: personOptions
    }
})

